package m.jclecai.com.fragment.klpk.pager;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import m.jclecai.com.R;
import m.jclecai.com.bean.klpk.bean.PokerBean;
import m.jclecai.com.utils.KlpkUtils;
import m.jclecai.com.utils.MakeRandomUtil;
import m.jclecai.com.view.klpk.KLPKRandomEffect;
import m.jclecai.com.view.klpk.PagerRecyclerAdapter;
import m.jclecai.com.view.klpk.Poker;
import m.jclecai.com.view.klpk.PokerGroup;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by andy on 2017/6/7.
 *
 * 这里是ViewPager里面的pager的Fragment相同的部分的抽出一个基类；
 *
 * 每一个Fragment都有一个Index对应着Bar上面的title显示的内容的一个索引；
 */



public abstract class BasePagerFragment extends Fragment {


    /**
     * index,每一个页面有一个特定的索引；
     */
    public int index=-1;

    //这个点击条目的获取的奖金；
    public int itemAward =-1;

    //这个是点击包选按钮时候，所获取的奖金；
    public int selectAllAward=-1;

    //底部的包选的几个组件；
    protected TextView mTvSelectedAllRules;
    protected View mLlSelected;
    public FrameLayout mFlSelectedAll;

    private PokerGroup mSelectAllPokerGroup;

    /**
     * 每一个页面至少需要选择几个才能下注；
     */
    int mAtMostSelected=0;
    private KLPKRandomEffect mKLPKRandomEffect;
    private String[] mMissingData;


    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {

        if(index<5 && index>=0){
            mAtMostSelected=1;
        }else{
            mAtMostSelected=index-4;
        }
        this.index = index;
    }

    public int getAtMostSelected() {
        return mAtMostSelected;
    }

    public void setAtMostSelected(int atMostSelected) {
        mAtMostSelected = atMostSelected;
    }

    /**
     * 判断是否可以下注；
     * @param selectItemNumber
     * @return
     */
    public boolean canBetting(int selectItemNumber){
        return selectItemNumber>=mAtMostSelected;
    }

    public int getItemAward() {
        return itemAward;
    }

    public void setItemAward(int itemAward) {
        this.itemAward = itemAward;
    }

    public int getSelectAllAward() {
        return selectAllAward;
    }

    public void setSelectAllAward(int selectAllAward) {
        this.selectAllAward = selectAllAward;
    }

    protected PagerRecyclerAdapter mMyAdapter;
    protected RecyclerView mRecyclerView;
    protected ArrayList<ArrayList<PokerBean>> mListData;
    protected RecyclerView.LayoutManager mLayoutManager;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = View.inflate(inflater.getContext(), R.layout.fragment_base_pager, null);

        mRecyclerView = ((RecyclerView) view.findViewById(R.id.recycler_view));

        mTvSelectedAllRules = ((TextView) view.findViewById(R.id.tv_selected_all_rules));
        mLlSelected = view.findViewById(R.id.ll_selected_all);

        //这里的话，是那个包选框框；
        mFlSelectedAll = ((FrameLayout) view.findViewById(R.id.fl_select_all));

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        //我们设置包选的按钮需要在设置adapter之前进行否者会出现一些问题；
        View selectAllView = View.inflate(getActivity(), R.layout.item_poke_pair, null);
        mSelectAllPokerGroup = (PokerGroup) selectAllView.findViewById(R.id.poker_group);
        ArrayList<PokerBean> pokerBeen = new ArrayList<>();
        //// TODO: 2017/6/11 这里我们之前设置的A对应1，2对应2，。。。j对应11这样的对应关系 这里的话，我们设置0是一个特殊的牌，包选；
        pokerBeen.add(new PokerBean(null, 0));
        //这里这个步骤其实进行一个操作就是将包选的按钮添加到PokerGroup中；所以这里的话，我们的FindViewById需要在这下面的一步完成；
        mSelectAllPokerGroup.newPokers(pokerBeen, Poker.TYPE_SELECT_ALL);
        final Button btnSelectAll = (Button) selectAllView.findViewById(R.id.btn_select_all);

        btnSelectAll.setText(getSelectAllTitle());
        mFlSelectedAll.addView(selectAllView);

        mSelectAllPokerGroup.showYiLouVisiable(false);
        mSelectAllPokerGroup.showMissNumberVisiable(false);

        mMyAdapter = getMyAdapter();
        mLayoutManager = getLayoutManager();




        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mMyAdapter);

        Observable.just("11")
                .flatMap(new Func1<String, Observable<ArrayList<ArrayList<PokerBean>>>>() {
                    @Override
                    public Observable<ArrayList<ArrayList<PokerBean>>> call(String o) {

                        mListData = initData();
                        return Observable.just(mListData);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ArrayList<ArrayList<PokerBean>> >() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        System.out.println("异常为："+e);
                    }

                    @Override
                    public void onNext(ArrayList<ArrayList<PokerBean>> arrayLists) {
                        mMyAdapter.addData(mListData);
                    }
                });




        //能够触发Checked状态改变的事件有两个，一个是条目的item被点击
        //一个是包选按钮被点击；
        mMyAdapter.setOnItemCheckedListener(new PagerRecyclerAdapter.OnItemCheckedListener() {
            @Override
            public void onItemChecked(int position, boolean isChecked) {
                //这里的话，我们肯定是需要执行回掉的；

                //判断是否有选中的条目；
                //选中了几个条目；
                //所有选中的条目的position;
                if (mOnCheckedChangeListener != null) {
                    mOnCheckedChangeListener.onCheckedChangeListener();
                }
            }
        });
        mSelectAllPokerGroup.setOnCheckedStatusChangeListener(new PokerGroup.OnCheckedStatusChangeListener() {
            @Override
            public void onCheckedStatusChange(boolean isChecked) {
                if (mOnCheckedChangeListener != null) {
                    mOnCheckedChangeListener.onCheckedChangeListener();
                }
            }
        });


        refreshMissData();
    }

    /**
     * 如果有包选按钮，设置包选按钮的内容；
     * @return
     */
    public String getSelectAllTitle() {
        return "";
    }

    /**
     * 这里表示是在pagerFragment里面，是否显示遗漏；
     * @param showMissing
     */
    public  void showMissNumber(boolean showMissing){
        //这里我们要做的一个操作就是，根据showMissing
        for (int i = 0; i < mMyAdapter.getData().size(); i++) {
            PokerGroup pokerGroup = getPokerGroupByPosition(i);
            if(i==0){
                pokerGroup.showYiLouVisiable(showMissing);
            }
            pokerGroup.showMissNumberVisiable(showMissing);
        }


    }

    public void setMissingData(String[] missingData) {

        mMissingData = missingData;
        if(mLayoutManager!=null && mLayoutManager.getChildCount()>0){
            refreshMissData();
        }
    }

    private void refreshMissData() {
        if (mMissingData != null ) {

            for (int i = 0; i < mMissingData.length; i++) {
                //这设置数据，没一期都有不同的数据，当期数切换了，我们是需要再次进行一个网络请求；
                PokerGroup pokerGroupByPosition = getPokerGroupByPosition(i);

                if (pokerGroupByPosition != null) {
                     pokerGroupByPosition.setMissNumber(mMissingData[i]);
                }
            }

        }
    }

    public interface OnCheckedChangeListener{
        void onCheckedChangeListener();
    }

    public  OnCheckedChangeListener mOnCheckedChangeListener;

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        mOnCheckedChangeListener = onCheckedChangeListener;
    }


    protected abstract ArrayList<ArrayList<PokerBean>> initData();

    public abstract   PagerRecyclerAdapter getMyAdapter();

    public abstract RecyclerView.LayoutManager getLayoutManager();
    /**
     * 清除所选的条目；
     * 一个是recyclerView的条目，一个是包选按钮的条目；
     */
    public void clear(){
        for (int i = 0; i < mLayoutManager.getItemCount(); i++) {
            setPositionItemChecked(i,false);
        }

        if (hasSelectAllChecked()) {
            mSelectAllPokerGroup.setChecked(false);
        }

    }

    /**
     * 随机下注，注意：这里的话，随机产生的一注是只会产生在item上面，不会产生在包选按钮上面；
     */
    public void randomBetting(){
        //这里的话，会随机根据至少的注数来产生下注；
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<mAtMostSelected;){
            double number = Math.random() * (mLayoutManager.getItemCount()-1);
            //将这个number转换为整型；加0.5 四舍五入
            int position = (int) (number + 0.5);
            if(!list.contains(position)){
                list.add(position);
            }
            i=list.size();
        }

        startAnimation(list);
    }


    /**
     * 开启动画；
     */
    private void startAnimation(final List<Integer> integers) {
        //这里表示动画的操作；
        List<PokerBean> pokerList=  new ArrayList<>();
        ArrayList<View> views=new ArrayList<>();

        if(index>=0 && index<5){

            List<String> pokerTypeList=new ArrayList<>();      //这里是扑克的花色的一个集合中；

            Integer integer = integers.get(0);  //机选到哪个位置；
            int poker=integer+1;    //映射为具体的牌型的位置；
            String pokerType = KlpkUtils.pokerType[index][poker];   //表示牌型；

            if(index==0 || index==2 || index==4){


                if(pokerType.contains("10")){
                    pokerType= pokerType.replaceAll("10","-"); //如果包含10，就将10 换成-
                }
                //将“AA" 弄成A，A
                String[] strings = pokerType.split("");       //如果是10的话，是两个字符，可能存在问题；
                if(index==0){
                    pokerTypeList= MakeRandomUtil.getWeiBall(4,2);
                }else{
                    if(index==4){
                        //这里表示豹子；不能同色
                        pokerTypeList=MakeRandomUtil.getWeiBall(4,3);
                    }else{
                        //顺子可以同色
                        pokerTypeList=MakeRandomUtil.getRandomWidthRepeat(4,3);
                    }

                }

                int i=0;
                for (String string : strings) {
                    if (!TextUtils.isEmpty(string)) {
                        PokerBean pokerBean = new PokerBean();
                        if(string.equals("-")){
                            // strs.add("10");
                            pokerBean.setNumStr("10");
                        }else{
                            pokerBean.setNumStr(string);
                        }
                        String s = pokerTypeList.get(i);
                        if(s.equals("0")){
                            //黑桃
                            pokerBean.setCategory(PokerBean.Category.spades);
                        }else if(s.equals("1")){
                            //红桃
                            pokerBean.setCategory(PokerBean.Category.hearts);
                        }else if(s.equals("2")){
                            //梅花
                            pokerBean.setCategory(PokerBean.Category.pulm_blossomm);
                        }else if(s.equals("3")){
                            //方块
                            pokerBean.setCategory(PokerBean.Category.box);
                        }
                        pokerList.add(pokerBean);
                        i++;
                    }
                }

            }else{
                //同花和同花顺1种花色，3张牌 花色有选中的条目决定，在这里是机选牌；


                //=====是什么牌型
                PokerBean.Category category=null;
                if (integer==0) {
                    //黑桃
                    category= PokerBean.Category.spades;
                }else if(integer==1){
                    //红桃
                    category=PokerBean.Category.hearts;
                }else if(integer==2){
                    //梅花
                    category= PokerBean.Category.pulm_blossomm;
                }else if(integer==3){
                    //方块
                    category=PokerBean.Category.box;
                }
                //============随机产生符合牌型的牌；
                if(index==1){
                    //同花，从13张牌中机选3张；不重复；
                    LinkedList<String> weiBall = MakeRandomUtil.getWeiBall(13, 3);

                    for (String s : weiBall) {

                        PokerBean pokerBean = new PokerBean();
                        int index = Integer.parseInt(s);
                        String s1 = KlpkUtils.pokerType[5][index];
                        pokerBean.setCategory(category);
                        pokerBean.setNumStr(s1);

                        pokerList.add(pokerBean);
                    }


                }else{
                    //同花顺，这里使用顺子的机选；

                    List<String> ball = MakeRandomUtil.getWeiBall(13, 1);

                    String s = ball.get(0);
                    int typeIndex = Integer.parseInt(s);
                    String pokerContent = KlpkUtils.pokerType[2][typeIndex];//牌型；

                    if(pokerContent.contains("10")){
                        pokerContent= pokerContent.replaceAll("10","-");
                    }
                    String[] split = pokerContent.split("");
                    for (String s1 : split) {
                        if (!TextUtils.isEmpty(s1)) {

                            PokerBean pokerBean = new PokerBean();
                            pokerBean.setCategory(category);
                            if(s1.equals("-")){
                                pokerBean.setNumStr("10");
                            }else{
                                pokerBean.setNumStr(s1);
                            }
                            pokerList.add(pokerBean);
                        }
                    }
                }
            }
            views.add(mLayoutManager.findViewByPosition(integer));
        }else {
            //最多选几个就几张牌；

            Collections.sort(integers);
            for (Integer integer : integers) {
                PokerBean effectPokerBean = new PokerBean();
                //这里的话，我们就机选一个花色吧；
                effectPokerBean.setNumStr(KlpkUtils.pokerType[5][integer]);
                effectPokerBean.setCategory(newCategory());

                pokerList.add(effectPokerBean);
                views.add(mLayoutManager.findViewByPosition(integer));
            }
        }

        mKLPKRandomEffect.setCenterPokers(pokerList);
        mKLPKRandomEffect.setDestView(views);
        mKLPKRandomEffect.start();
        //我们在这里是实现动画的效果；
        mKLPKRandomEffect.setOnAnimatorListnener(new KLPKRandomEffect.OnAnimatorListnener() {
            @Override
            public void onAnimatorStart() {

            }

            @Override
            public void onAnimatorEnd() {
                //结束的时候选中一个
                for (Integer position : integers) {
                    setPositionItemChecked(position,true);
                }
            }
        });

    }


    /**
     * 机选一个花色；
     * @return
     */
    public PokerBean.Category newCategory(){
        List<String> ball = MakeRandomUtil.getRandomWidthRepeat(4, 1);
        String s = ball.get(0);
        int i = Integer.parseInt(s);
        if(i==0){
            return PokerBean.Category.spades;
        }else if(i==1){
            return PokerBean.Category.hearts;
        }else if(i==2){
            return PokerBean.Category.pulm_blossomm;
        }else if(i==3){
            return PokerBean.Category.box;
        }

        return null;
    }

    /**
     * 改变RecyclerView里面的具体位置条目的状态；
     * @param position recyclerView具体的位置；
     * @param isChecked 要改变成什么样子的状态；
     */
    public void setPositionItemChecked(int position,boolean isChecked){
        System.out.println("position: "+position);
        PokerGroup pokerGroup = getPokerGroupByPosition(position);
        pokerGroup.setChecked(isChecked);
    }

    /**
     * 通过position来获取PokerGroup对象；
     * @param position
     * @return
     */
    protected PokerGroup getPokerGroupByPosition(int position) {
        try {
            View itemView = mLayoutManager.findViewByPosition(position);
            return (PokerGroup) itemView.findViewById(R.id.poker_group);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 判断是否有pager中是否有被选中的；
     */
    public boolean hasChecked(){

        if(!hasSelectAllChecked()&&!hasItemChecked()){
            return false;
        }
        return true;
    }

    //判断包选是否被选中；
    public boolean hasSelectAllChecked(){
        return mSelectAllPokerGroup.isChecked();
    }

    /**
     * 条目是否有被选中的；
     * @return
     */
    public boolean hasItemChecked(){
        return  getSelectedItemIndexs().size()==0?false:true;
    }

    /**
     * 将选中的条目的Positions通过List集合将其Position传递出去；
     * @return
     */
    public List<Integer> getSelectedItemIndexs(){

        List<Integer> list=new ArrayList<>();
        for (int i = 0; i < mLayoutManager.getItemCount(); i++) {
            PokerGroup pokerGroup = getPokerGroupByPosition(i);
            if (pokerGroup.isChecked()) {
                list.add(i);
            }
        }
        return list;
    }

    /**
     * 将规则里面的字符串，转换为相应的样式
     * @param rules
     * @return
     */
    public SpannableString getSelectedAllRichText(String rules){

        SpannableString spannableString = new SpannableString(rules);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(0xFFfec345);
        int startIndex = rules.indexOf("中奖")+"中奖".length();
        spannableString.setSpan(foregroundColorSpan,startIndex,rules.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

}
